﻿namespace EasyGo.Web.Authentication.Impl
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using EasyGo.Domain.Model;
    using EasyGo.Data.Dao;
    using System.Web.Security;
    using System.Web.Configuration;
    using EasyGo.Services;

    public class AuthenticationService : Service, IAuthenticationService
    {
        private const string PASS_SALT = "ascq12%";

        private readonly IUserAccountDao _userAccountDao;

        public AuthenticationService(IUserAccountDao userAccountDao)
        {
            this._userAccountDao = userAccountDao;
        }

        public UserInfo ValidateUser(string email, string pass)
        {
            var salted = string.Concat(PASS_SALT, email, pass);
            string password = FormsAuthentication.HashPasswordForStoringInConfigFile(salted, FormsAuthPasswordFormat.SHA1.ToString());
            return _userAccountDao.ValidateUser(email, password);
        }

        public MembershipCreateStatus CreateUser(UserAccount user)
        {
            if (string.IsNullOrEmpty(user.Pass))
            {
                user.Pass = Membership.GeneratePassword(6, 2);
            }
            user.Pass = FormsAuthentication.HashPasswordForStoringInConfigFile(string.Concat(PASS_SALT, user.Email, user.Pass), 
                FormsAuthPasswordFormat.SHA1.ToString());
            int result = this._userAccountDao.CreateUser(user);
            this.SaveChanges();
            return (MembershipCreateStatus)result;
        }


        public void Authenticate(UserInfo info, bool persist)
        {
            FormsAuthentication.SetAuthCookie(info.Email, persist);
        }

        public void SignOut()
        {
            FormsAuthentication.SignOut();
        }

    }
}